/*
 *  Copyright 1999-2019 Seata.io Group.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package io.seata.core.exception;

import io.seata.config.Configuration;
import io.seata.config.ConfigurationFactory;
import io.seata.core.protocol.ResultCode;
import io.seata.core.protocol.transaction.AbstractTransactionRequest;
import io.seata.core.protocol.transaction.AbstractTransactionResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The type Abstract exception handler.
 * //yangyc Callback 、AbstractCallback 是 AbstractExceptionHandler 的内部接口和内部类，
 * AbstractCallback 抽象类实现了接口 Callback 的三个方法，还有一个 execute() 未实现。
 * AbstractExceptionHandler 使用了 AbstractCallback 作为模板方法的参数，并使用了其实现的三个方法，但是 execute() 方法仍留给子类实现
 *
 *  onSuccess、onTransactionException、onException 在 AbstarctCallback 中已经被实现，
 *  execute 则由AbstractExceptionHandler 子类即负责不同事务模式的 handler 类进行实现。
 *  AbstractExceptionHandler 目前有两个子类：AbstractTCInboundHandler 负责处理全局事务的业务，AbstractRMHandler 负责处理分支事务的业务。
 * @author sharajava
 */
public abstract class AbstractExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractExceptionHandler.class);

    /**
     * The constant CONFIG.
     */
    protected static final Configuration CONFIG = ConfigurationFactory.getInstance();

    /**
     * The interface Callback.
     * //yangyc AbstractExceptionHandler 的内部接口，
     *
     * @param <T> the type parameter
     * @param <S> the type parameter
     */
    public interface Callback<T extends AbstractTransactionRequest, S extends AbstractTransactionResponse> {
        /**
         * Execute.
         *
         * @param request  the request
         * @param response the response
         * @throws TransactionException the transaction exception
         */
        void execute(T request, S response) throws TransactionException;

        /**
         * on Success
         *
         * @param request
         * @param response
         */
        void onSuccess(T request, S response);

        /**
         * onTransactionException
         *
         * @param request
         * @param response
         * @param exception
         */
        void onTransactionException(T request, S response, TransactionException exception);

        /**
         * on other exception
         *
         * @param request
         * @param response
         * @param exception
         */
        void onException(T request, S response, Exception exception);

    }

    /**
     * //yanygc AbstractExceptionHandler 的内部类，
     * AbstractCallback 抽象类实现了接口 Callback 的三个方法，还有一个 execute() 未实现
     * @param <T>
     * @param <S>
     */
    public abstract static class AbstractCallback<T extends AbstractTransactionRequest, S extends AbstractTransactionResponse>
        implements Callback<T, S> {

        @Override
        public void onSuccess(T request, S response) {
            response.setResultCode(ResultCode.Success);
        }

        @Override
        public void onTransactionException(T request, S response,
            TransactionException tex) {
            response.setTransactionExceptionCode(tex.getCode());
            response.setResultCode(ResultCode.Failed);
            response.setMsg("TransactionException[" + tex.getMessage() + "]");
        }

        @Override
        public void onException(T request, S response, Exception rex) {
            response.setResultCode(ResultCode.Failed);
            response.setMsg("RuntimeException[" + rex.getMessage() + "]");
        }
    }

    /**
     * Exception handle template.
     * //yangyc 从对外暴露的角度看 AbstractExceptionHandler 定义了一个带有异常处理的模板方法，
     * 模板中有四个行为，在不同的情况下执行，其中三种行为已经实现，执行的行为交由子类自行实现
     *
     * 先使用模板方法，把事务业务流程定下来，再通过回调，把具体执行事务业务的方法，留给子类实现。设计的非常巧妙
     *
     * @param callback the callback
     * @param request  the request
     * @param response the response
     */
    public <T extends AbstractTransactionRequest, S extends AbstractTransactionResponse> void exceptionHandleTemplate(Callback<T, S> callback, T request, S response) {
        try {
            //yanygc 执行事务业务的方法
            callback.execute(request, response);
            //yangyc 设置response返回码
            callback.onSuccess(request, response);
        } catch (TransactionException tex) {
            LOGGER.error("Catch TransactionException while do RPC, request: {}", request, tex);
            //yangyc 设置response返回码并设置msg
            callback.onTransactionException(request, response, tex);
        } catch (RuntimeException rex) {
            LOGGER.error("Catch RuntimeException while do RPC, request: {}", request, rex);
            //yangyc 设置response返回码并设置msg
            callback.onException(request, response, rex);
        }
    }

}
